using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using Traceability.API.APPLications.Commands.TraceabilityInfoshow;
using Traceability.API.Services;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.TraceabilityInfoshow
{
    /// <summary>
    /// 批量物理删除溯源信息命令处理程序（已改为物理删除）
    /// </summary>
    public class BatchDeleteTraceabilityInfoCommandHandler : IRequestHandler<BatchDeleteTraceabilityInfoCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<TraceabilityInfo> _traceabilityRepository;
        private readonly TraceabilityRedisHelper _redisHelper;
        private readonly ILogger<BatchDeleteTraceabilityInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="traceabilityRepository">溯源信息仓储</param>
        /// <param name="redisHelper">Redis帮助类</param>
        /// <param name="logger">日志记录器</param>
        public BatchDeleteTraceabilityInfoCommandHandler(
            IBaseRepository<TraceabilityInfo> traceabilityRepository,
            TraceabilityRedisHelper redisHelper,
            ILogger<BatchDeleteTraceabilityInfoCommandHandler> logger = null)
        {
            _traceabilityRepository = traceabilityRepository;
            _redisHelper = redisHelper;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除请求
        /// </summary>
        /// <param name="request">批量删除请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public async Task<APIResult<bool>> Handle(BatchDeleteTraceabilityInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();

            // 开始数据库事务
            using var transaction = await _traceabilityRepository.Context.Database.BeginTransactionAsync(cancellationToken);

            try
            {
                // 检查请求参数
                if (request.TraceabilityIds == null)
                {
                    result.Code = APIEnum.操作失败;
                    result.Message = "TraceabilityIds不能为null";
                    return result;
                }

                if (request.TraceabilityIds.Count == 0)
                {
                    result.Code = APIEnum.操作失败;
                    result.Message = "TraceabilityIds不能为空集合";
                    return result;
                }

                // 记录日志
                _logger?.LogInformation("批量删除请求参数: IDs={0}, DeleteBy={1}",
                    JsonSerializer.Serialize(request.TraceabilityIds), request.DeleteBy);

                // 查找要批量删除的记录
                var query = _traceabilityRepository.GetAll()
                    .Where(t => request.TraceabilityIds.Contains(t.TraceabilityId));

                // 先获取查询的SQL以进行日志记录
                string sql = "查询条件: TraceabilityIds in [" + string.Join(",", request.TraceabilityIds) + "]";
                _logger?.LogInformation("批量物理删除SQL查询: {0}", sql);

                var traceabilityList = await query.ToListAsync(cancellationToken);

                // 记录查询结果
                _logger?.LogInformation("批量物理删除查询结果: 找到{0}条记录", traceabilityList?.Count ?? 0);

                // 明确检查列表是否为null或空
                if (traceabilityList == null || traceabilityList.Count == 0)
                {
                    result.Code = APIEnum.查询失败;
                    result.Message = "未找到要删除的记录";
                    return result;
                }

                _logger?.LogInformation("找到 {Count} 条要物理删除的溯源信息", traceabilityList.Count);

                // 批量物理删除
                var deleteResult = await _traceabilityRepository.DeleteRange(traceabilityList);

                _logger?.LogInformation("批量物理删除数据库操作结果: {0}条记录已删除", deleteResult);

                if (deleteResult <= 0)
                {
                    await transaction.RollbackAsync(cancellationToken);
                    result.Code = APIEnum.操作失败;
                    result.Message = "数据库批量物理删除失败";
                    return result;
                }

                // 提交数据库事务
                await transaction.CommitAsync(cancellationToken);
                _logger?.LogInformation("批量物理删除事务已提交: {0}条记录", traceabilityList.Count);

                // 事务成功后从Redis缓存中移除
                try
                {
                    // 批量移除Redis缓存
                    foreach (var id in request.TraceabilityIds)
                    {
                        await _redisHelper.RemoveTraceabilityInfoAsync(id);
                    }

                    // 清除列表缓存，以便下次获取最新数据
                    await _redisHelper.RemoveTraceabilityListAsync();

                    _logger?.LogInformation("批量物理删除Redis缓存移除完成: {0}条记录", traceabilityList.Count);
                }
                catch (Exception redisEx)
                {
                    // Redis操作失败不影响主要业务逻辑，只记录日志
                    _logger?.LogWarning(redisEx, "批量物理删除Redis缓存移除失败，但数据库操作已成功: {0}条记录", traceabilityList.Count);
                }

                result.Code = APIEnum.删除成功;
                result.Message = $"成功物理删除{traceabilityList.Count}条记录";
                result.Data = true;
            }
            catch (Exception ex)
            {
                // 回滚事务
                try
                {
                    await transaction.RollbackAsync(cancellationToken);
                    _logger?.LogInformation("批量物理删除事务已回滚");
                }
                catch (Exception rollbackEx)
                {
                    _logger?.LogError(rollbackEx, "批量物理删除事务回滚失败");
                }

                _logger?.LogError(ex, "批量物理删除处理时发生异常");
                result.Code = APIEnum.操作失败;
                result.Message = $"批量物理删除失败: {ex.Message}";
                result.Data = false;
            }

            return result;
        }
    }
} 